<template>
  <div class="user-center-page">
    <Header />

    <!-- 账号信息区域 -->
    <div class="account-info-section">
      <div class="section-header">
        <h3>账号信息</h3>
      </div>
      <div class="account-content">
        <div class="user-avatar">
          <div class="avatar-circle">
            <img v-if="avatarDisplay" :src="proxy.$buildUrl(avatarDisplay)" alt="头像" class="avatar-image" />
            <span v-else class="avatar-text">{{ displayName?.charAt(0) || 'U' }}</span>
          </div>
        </div>
        <div class="user-info">
          <h3 class="user-name">{{ displayName }}</h3>
          <!-- <p class="user-level">{{ userInfo?.memberLevel || '普通会员' }} · {{ userInfo?.memberSince || '新会员' }}</p> -->

          <!-- 余额信息 -->
          <div class="balance-info">
            <div class="balance-item">
              <span class="balance-label">账户余额</span>
              <span class="balance-amount" style="margin-left: 10px">¥{{ balance || '0.00' }}</span>
            </div>
          </div>
          <div class="user-actions">
            <div class="action-item" @click="toProfile">
              <span>编辑账号/密码</span>
            </div>
            <div class="action-item" @click="toAddress">
              <span>收货地址管理</span>
            </div>
            <div class="action-item" @click="toBalance">
              <span>余额明细</span>
            </div>
            <div class="action-item" @click="logout">
              <span>账号注销</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 我的订单区域 -->
    <div class="order-section">
      <div class="section-header">
        <h3>我的订单</h3>
      </div>
      <div class="order-menu">
        <div class="order-menu-item" @click="toOrder">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_03.jpg" alt="全部订单" class="icon-image" />
          </div>
          <span>全部订单</span>
        </div>
        <div class="order-menu-item" @click="toOrder">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_05.jpg" alt="待付款" class="icon-image" />
          </div>
          <span>待付款</span>
        </div>
        <div class="order-menu-item" @click="toOrder">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_07.jpg" alt="待发货/备货" class="icon-image" />
          </div>
          <span>待发货/备货</span>
        </div>
        <div class="order-menu-item" @click="toOrder">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_09.jpg" alt="待收货/提货" class="icon-image" />
          </div>
          <span>待收货/提货</span>
        </div>
      </div>
    </div>

    <!-- 会员权益区域 -->
    <div class="benefits-section">
      <div class="section-header">
        <h3>会员权益</h3>
      </div>
      <div class="benefits-menu">
        <div class="benefit-menu-item" @click="toCoupon">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_16.jpg" alt="优惠券" class="icon-image" />
          </div>
          <span>优惠券</span>
        </div>
        <div class="benefit-menu-item" @click="toOrder">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_17.jpg" alt="退换货" class="icon-image" />
          </div>
          <span>退换货</span>
        </div>
        <div class="benefit-menu-item" @click="contactService">
          <div class="menu-icon">
            <img src="@/assets/images/用户中心_19.jpg" alt="在线客服" class="icon-image" />
          </div>
          <span>在线客服</span>
        </div>
      </div>
    </div>

    <BottomNavbar v-if="isMobile" />
    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, computed, onMounted } from 'vue'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import BottomNavbar from '@/components/BottomNavbar.vue'
  import { useRouter } from 'vue-router'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()

  // 从store获取用户状态（保持响应性）
  const isLoggedIn = computed(() => userStore.isLoggedIn)
  const userInfo = computed(() => userStore.userInfo)
  const displayName = computed(() => userStore.displayName)
  const avatarDisplay = computed(() => userStore.avatarDisplay)
  const companyId = computed(() => userStore.companyId)
  const dealerInfo = computed(() => userStore.dealerInfo)
  const balance = ref(0)

  // 组件挂载时获取用户信息
  onMounted(async () => {
    userStore.initUserData()
    if (!(companyId.value && companyId.value !== '') || !(dealerInfo.value.id && dealerInfo.value.id !== '')) {
      await userStore.getCompanyInfo()
    }
    if (isLoggedIn.value) {
      await userStore.getUserInfo()
      loadAccountInfo()
    }
  })

  const loadAccountInfo = () => {
    apiUser.GetAccountInfo().then(async (res) => {
      if (res.data && res.data.balance) {
        balance.value = parseFloat(res.data.balance)
      }
    })
  }

  const router = useRouter()
  const toCoupon = () => {
    jump('/coupon')
  }

  const toOrder = () => {
    jump('/orders')
  }

  const toAddress = () => {
    jump('/address')
  }

  const toBalance = () => {
    jump('/balance')
  }

  const toProfile = () => {
    jump('/profile')
  }

  const jump = (path) => {
    // 滚动到顶部
    window.scrollTo(0, 0)
    router.push({
      path,
    })
  }

  const logout = () => {
    userStore.logout()
    jump('/')
  }

  const contactService = () => {
    // 实际应用中，这里可以跳转到在线客服页面或弹出聊天窗口
    // 复制小程序路径（如 pages/contact/index），并生成 URL Scheme（在微信开放平台生成）

    // 判断是否在微信内
    const isWeixin = /MicroMessenger/i.test(navigator.userAgent)
    if (isWeixin) {
      // 引导用户跳转小程序客服
      window.location.href = 'weixin://dl/business/?t=pages/user/user'
    } else {
      ElMessage.warning('请在微信内打开')
    }
  }

  const deviceInfo = ref({
    type: '',
    os: '',
    browser: '',
    screenWidth: 0,
  })
  const getDeviceInfo = () => {
    const userAgent = navigator.userAgent.toLowerCase()
    const screenWidth = window.innerWidth

    // 检测操作系统
    let os = 'Unknown'
    if (userAgent.includes('android')) os = 'Android'
    else if (userAgent.includes('iphone') || userAgent.includes('ipad')) os = 'iOS'
    else if (userAgent.includes('windows')) os = 'Windows'
    else if (userAgent.includes('mac')) os = 'macOS'
    else if (userAgent.includes('linux')) os = 'Linux'

    // 检测浏览器
    let browser = 'Unknown'
    if (userAgent.includes('chrome')) browser = 'Chrome'
    else if (userAgent.includes('firefox')) browser = 'Firefox'
    else if (userAgent.includes('safari')) browser = 'Safari'
    else if (userAgent.includes('edge')) browser = 'Edge'

    // 检测设备类型
    let type = 'Desktop'
    if (userAgent.includes('mobile') || screenWidth <= 768) type = 'Mobile'
    else if (userAgent.includes('tablet') || (screenWidth > 768 && screenWidth <= 1024)) type = 'Tablet'

    deviceInfo.value = { type, os, browser, screenWidth }

    return { type, os, browser, screenWidth }
  }

  // 检测是否为移动设备
  const isMobile = ref(false)
  const checkMobile = () => {
    const { type, screenWidth } = getDeviceInfo()
    const userAgent = navigator.userAgent.toLowerCase()

    // 更精确的移动设备检测
    const mobileKeywords = ['mobile', 'android', 'iphone', 'ipod', 'blackberry', 'windows phone']
    const tabletKeywords = ['ipad', 'tablet']

    const isMobileDevice = mobileKeywords.some((keyword) => userAgent.includes(keyword))
    const isTabletDevice = tabletKeywords.some((keyword) => userAgent.includes(keyword))
    const isSmallScreen = screenWidth <= 768
    const isMediumScreen = screenWidth > 768 && screenWidth <= 1024

    // 移动设备或小屏幕显示移动端界面
    // 平板设备根据屏幕宽度决定
    isMobile.value = isMobileDevice || isSmallScreen || (isTabletDevice && isMediumScreen)
  }
  checkMobile()
</script>

<style scoped>
  .user-center-page {
    width: 1200px;
    margin: 0 auto;
    background-color: white;
  }

  /* 账号信息区域 */
  .account-info-section {
    margin: 30px auto;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }

  .section-header {
    background-color: #1c705e;
    padding: 15px 20px;
  }

  .section-header h3 {
    color: #fff;
    margin: 0;
    font-size: 18px;
    font-weight: normal;
  }

  .account-content {
    display: flex;
    align-items: center;
    padding: 30px;
    background-color: #f6f7f8;
  }

  .user-avatar {
    margin-right: 30px;
  }

  .avatar-circle {
    width: 110px;
    height: 110px;
    border-radius: 50%;
    background-color: #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #666;
    font-weight: bold;
  }

  .user-info {
    flex: 1;
  }

  .balance-info {
    padding-bottom: 10px;
  }

  .user-name {
    font-size: 20px;
    color: #333;
    margin: 0 0 20px 0;
    font-weight: normal;
  }

  .user-actions {
    display: flex;
    gap: 40px;
    margin-bottom: 15px;
  }

  .user-actions:last-child {
    margin-bottom: 0;
  }

  .action-item {
    color: #52a58a;
    cursor: pointer;
    font-size: 14px;
    text-decoration: none;
  }

  .action-item:hover {
    text-decoration: underline;
  }

  /* 订单区域 */
  .order-section,
  .benefits-section {
    margin: 30px auto;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }

  .order-menu,
  .benefits-menu {
    display: flex;
    justify-content: space-around;
    padding: 40px 20px;
    background-color: #f6f7f8;
  }

  .order-menu-item,
  .benefit-menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    flex: 1;
    max-width: 200px;
  }

  .menu-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .icon-image {
    width: 50px;
    height: 50px;
    object-fit: contain;
  }

  .order-menu-item span,
  .benefit-menu-item span {
    font-size: 14px;
    color: #333;
    text-align: center;
    line-height: 1.4;
  }

  /* 响应式调整 */
  @media (max-width: 1024px) {
    .user-center-page {
      width: 95%;
      margin: 0 auto;
    }
  }

  @media (max-width: 768px) {
    .account-content {
      flex-direction: column;
      text-align: center;
    }

    .user-avatar {
      margin-right: 0;
      margin-bottom: 20px;
    }

    .user-actions {
      justify-content: center;
      gap: 20px;
    }

    .order-menu,
    .benefits-menu {
      flex-direction: row !important;
      flex-wrap: wrap;
      gap: 20px;
      padding: 30px 15px;
    }

    .order-menu-item,
    .benefit-menu-item {
      width: 15%;
      max-width: none;
    }

    .order-menu-item span {
      font-size: 10px;
    }

    .benefit-menu-item span {
      font-size: 10px;
    }

    .menu-icon {
      width: 60px;
      height: 60px;
    }

    .icon-image {
      width: 30px;
      height: 30px;
    }
  }

  @media (max-width: 480px) {
    .user-actions {
      flex-direction: column;
      gap: 10px;
      align-items: center;
    }

    .order-menu,
    .benefits-menu {
      flex-direction: column;
      gap: 30px;
      align-items: center;
    }

    .order-menu-item,
    .benefit-menu-item {
      width: 15%;
      max-width: 100px;
    }

    .order-menu-item span {
      font-size: 10px;
    }

    .benefit-menu-item span {
      font-size: 10px;
    }

    .menu-icon {
      width: 60px;
      height: 60px;
    }

    .icon-image {
      width: 30px;
      height: 30px;
    }
  }
</style>
